import { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { Md5 } from 'ts-md5'
import { typeOf, deepCopy } from '@/utils/cloud/utils'

type ResponseData = {
  code: number
  msg: any
}

const cache: any = {}

const getKey = (keyData: InternalAxiosRequestConfig) => {
  let { url, method, params, data } = keyData
  let data1 = null
  if (typeOf(data) === 'string') {
    data1 = JSON.parse(data)
    delete data1.id
  } else if (data) {
    data1 = deepCopy(data)
    delete data1.id
  }
  let keyUrl = `url:${url}&method:${method}&params:${JSON.stringify(params)}&data:${JSON.stringify(data1)}`
  const md5 = new Md5()
  const md5key = md5.appendStr(keyUrl).end() + ''

  return md5key
}

// 设置缓存
export const setCache = (keyData: InternalAxiosRequestConfig, value: ResponseData) => {
  const key = getKey(keyData)
  cache[key].data = value
  if (cache[key].request_list.length) {
    cache[key].request_list.forEach((cb: any) => {
      cb(value)
    })
  }
  cache[key].request_list = []
  setTimeout(() => {
    delete cache[key]
  }, 5000)
}

// 获取缓存
export const getCache = (keyData: InternalAxiosRequestConfig, callback: any) => {
  const key = getKey(keyData)
  if (!cache[key]) {
    cache[key] = { data: null, request_list: [] }
  } else if (!cache[key].data) {
    cache[key].request_list.push(callback)
  } else {
    callback(cache[key].data)
  }
}

export const hasCache = (keyData: InternalAxiosRequestConfig) => {
  const key = getKey(keyData)
  let isFlag = cache[key] !== undefined
  if (!cache[key]) cache[key] = { data: null, request_list: [] }
  return isFlag
}
